package org.kotemaru.browser;
import org.kotemaru.util.IOUtil;
import java.net.URI;
import java.net.URLDecoder;

import org.apache.commons.beanutils.BeanUtils;

public class ActionBrowserFrame extends BrowserFrame {
	static final String ACTION_PREFIX = "http://action/";

	private String basePkg;
	
	public ActionBrowserFrame(String title, String pkg) {
		super(title);
		basePkg = pkg;
		setHome(ACTION_PREFIX+"Main");
	}
	
	public boolean isAllowUrl(String url) {
		return url.startsWith("about:");
	}
	public boolean isApplicationUrl(String url) {
		return url.startsWith(ACTION_PREFIX);
	}
	public void doApplicationUrl(String urlStr) throws Exception {
		URI uri = new URI(urlStr);
		String name = uri.getPath();
		if (name.indexOf('.') == -1) {
			doAction(uri);
		} else {
			String html = IOUtil.getResource(this.getClass(), name);
			browser.setText(html);
		}
	}

	protected void doAction(URI uri) throws Exception {
		String name = uri.getPath();
		String cname = basePkg+name.replace('/', '.')+"Action";
		Class cls = Class.forName(cname);
		Action action = (Action) cls.newInstance();
		action.postBrowserFrame(this);
		copyQuery(uri, action);
		Navigator navi = action.execute();
		if (navi == null) return;
		if (navi instanceof RedirectNavigator) {
			browser.setUrl(navi.getResource());
		} else {
			browser.setText(navi.getHtml());
		}
	}
	
	protected void copyQuery(URI uri, Action action)  throws Exception{
		String query = uri.getQuery();
		if (query == null) return;
		String[] params = query.split("&");
		for (int i=0; i<params.length; i++) {
			String[] kv = params[i].split("=");
			if (kv.length == 2) {
				String key = kv[0];
				String val = URLDecoder.decode(kv[1], "UTF-8");
				BeanUtils.setProperty(action, key, val);
			}
		}
	}
}
